from django.shortcuts import render,HttpResponse,reverse
from .models import *
# Create your views here.
# 使用objects.all获得所有的数据值
def index_handler(request):
    user=User.objects.all()
    print(user)
    return render(request,'index.html',context={'user':user})

print(index_handler)

#
def add_handler(request):
    # 传输方式如果是GET，渲染后再传入；如果是POST，那么获取HTML通过form传入的值
    user=User()
    if request.method == "GET":
        return render(request,'add.html')
    else:
        user.username=request.POST.get('username')
        user.password=request.POST.get('password')
        user.age=request.POST.get('age')
        user.email=request.POST.get('email')
        # 防止传入空值，使用try except获取不合格的值，抛出友好的错误信息
        # try:
        user.save()
        # save方法存储数据
        return render(request,'result.html',{'message':'保存成功'})
        # except:
        #     return render(request,'result.html',{'message':'保存失败'})


# update需要获取传输进来的id值
def update_handler(request,id):
    user=User.objects.get(id=id)
    if request.method=="GET":
        return render(request,'update.html',context={'user':user})
    else:
        user.username=request.POST.get('username')
        user.password=request.POST.get('password')
        user.age=request.POST.get('age')
        user.email=request.POST.get('email')
        try:
            user.save()
            return render(request,'result.html',{'message':'修改成功'})
        except:
            return render(request,'result.html',{'messgae':'修改失败'})

# delete方法需要获取传输的id值；filter是筛选条件
def delete_handler(request,id):
    try:
        User.objects.filter(id=id).delete()
        return render(request,'result.html',{'message':'删除成功'})
    except:
        return render(request,'result.html',{'message':'删除失败'})